<template>
  <div class="hotel-location">
    <div class="section-header">
      <environment-outlined class="section-icon" />
      <h2>位置与交通</h2>
    </div>

    <div class="location-container">
      <div class="map-container" ref="mapContainer"></div>
      <div class="location-info">
        <div class="address-card">
          <h3>酒店地址</h3>
          <p class="address">
            <environment-outlined />
            {{ locationData?.address || address }}
          </p>
          <a-button type="primary" class="navigation-btn" @click="navigateToHotel">
            <template #icon><compass-outlined /></template>
            导航到这里
          </a-button>
        </div>
        
        <div class="transportation-card">
          <h3>交通信息</h3>
          <a-tabs default-active-key="1" class="custom-tabs">
            <a-tab-pane key="1" tab="公共交通">
              <div v-if="!hasTransportationData || publicTransport.length === 0" class="empty-info">
                <car-outlined class="empty-icon" />
                <p>暂无公共交通信息</p>
              </div>
              <ul v-else class="transport-list">
                <li v-for="(item, index) in publicTransport" :key="index">
                  <car-outlined class="transport-icon" />
                  <span>{{ item }}</span>
                </li>
              </ul>
            </a-tab-pane>
            <a-tab-pane key="2" tab="机场/车站">
              <div v-if="!hasTransportationData || airportTransport.length === 0" class="empty-info">
                <global-outlined class="empty-icon" />
                <p>暂无机场/车站信息</p>
              </div>
              <ul v-else class="transport-list">
                <li v-for="(item, index) in airportTransport" :key="index">
                  <global-outlined class="transport-icon" />
                  <span>{{ item }}</span>
                </li>
              </ul>
            </a-tab-pane>
          </a-tabs>
        </div>

        <div class="nearby-card">
          <h3>周边设施</h3>
          <div v-if="!hasAttractionsData || attractionsInfo.length === 0" class="empty-info">
            <environment-outlined class="empty-icon" />
            <p>暂无周边设施信息</p>
          </div>
          <div v-else class="nearby-grid">
            <div v-for="(item, index) in attractionsInfo" :key="index" class="nearby-item">
              <component :is="getAttractionIcon(item.type)" class="nearby-icon" />
              <span>{{ item.name }} ({{ item.distance }})</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// 声明百度地图全局对象
declare global {
  interface Window {
    BMap: any;
    initBaiduMap: () => void;
  }
}

import { ref, onMounted, watch, computed } from 'vue'
import { 
  EnvironmentOutlined, 
  CompassOutlined, 
  CarOutlined, 
  GlobalOutlined,
  ShoppingOutlined,
  CoffeeOutlined,
  BankOutlined,
  MedicineBoxOutlined
} from '@ant-design/icons-vue'
import { useHotelDetailStore } from '@/stores/hotelDetailStrore'
import { storeToRefs } from 'pinia'

const props = defineProps<{
  address: string
  hotelId: string | number
}>()

const hotelDetailStore = useHotelDetailStore()
const { hotelDetail, loading } = storeToRefs(hotelDetailStore)

const mapContainer = ref<HTMLElement | null>(null)

// 使用store中的位置信息
const locationData = computed(() => hotelDetail.value.location)

// 交通信息，仅使用API返回的数据
const transportInfo = computed(() => {
  if (locationData.value && locationData.value.transportation) {
    try {
      // 确保是数组
      const transportationData = locationData.value.transportation;
      if (Array.isArray(transportationData) && transportationData.length > 0) {
        // 转换成字符串格式
        return transportationData.map((item: any) => {
          if (typeof item === 'string') return item;
          // 构造交通信息描述
          let description = '';
          if (item.name) {
            description += item.name;
          }
          if (item.type) {
            if (description) description += ' (';
            description += getTransportTypeText(item.type);
            if (description && !description.endsWith(')')) description += ')';
          }
          if (item.distance && item.unit) {
            description += ` 距离${item.distance}${item.unit}`;
          } else if (item.distance) {
            description += ` 距离${item.distance}米`;
          }
          return description || '未知交通';
        });
      }
    } catch (error) {
      console.error('处理交通信息失败:', error);
    }
  }
  
  // 没有数据时返回空数组
  return [];
});

// 转换交通类型
const getTransportTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    'subway': '地铁',
    'bus': '公交',
    'train': '火车',
    'airport': '机场',
    'taxi': '出租车站'
  };
  return typeMap[type] || type;
};

// 分类后的交通信息
const publicTransport = computed(() => {
  return transportInfo.value.filter(item => {
    return typeof item === 'string' && (
      item.includes('地铁') || 
      item.includes('公交') || 
      item.includes('公共') ||
      item.includes('公交车')
    );
  });
});

const airportTransport = computed(() => {
  return transportInfo.value.filter(item => {
    return typeof item === 'string' && (
      item.includes('机场') || 
      item.includes('站') || 
      item.includes('车站') || 
      item.includes('火车') ||
      item.includes('高铁')
    );
  });
});

// 周边景点信息
const attractionsInfo = computed(() => {
  if (locationData.value && locationData.value.attractions) {
    try {
      // 确保是数组
      const attractionsData = locationData.value.attractions;
      if (Array.isArray(attractionsData) && attractionsData.length > 0) {
        return attractionsData.map((item: any) => {
          if (typeof item === 'object') {
            // 构造距离表示
            let distanceText = '';
            if (item.distance) {
              // 确保单位值正确转换
              const unitMap: Record<string, string> = {
                'km': '公里',
                'm': '米',
                'min': '分钟'
              };
              const unitDisplay = unitMap[item.unit] || item.unit || 'm';
              distanceText = `${item.distance}${unitDisplay}`;
            }
            
            return {
              name: item.name || '',
              distance: distanceText || '附近',
              type: item.type || 'landmark'
            };
          } else if (typeof item === 'string') {
            return { name: item, distance: '附近', type: 'landmark' };
          }
          return { name: '未知景点', distance: '未知', type: 'landmark' };
        });
      }
    } catch (error) {
      console.error('处理周边景点信息失败:', error);
    }
  }
  
  // 没有数据时返回空数组
  return [];
});

// 获取景点图标
const getAttractionIcon = (type: string) => {
  const iconMap: Record<string, any> = {
    'shopping': ShoppingOutlined,
    'coffee': CoffeeOutlined,
    'bank': BankOutlined,
    'medicine': MedicineBoxOutlined,
    'park': GlobalOutlined,
    'museum': GlobalOutlined,
    'landmark': EnvironmentOutlined
  };
  
  return iconMap[type] || ShoppingOutlined;
};

const initMap = () => {
  // 确保BMap已加载
  if (typeof window.BMap === 'undefined') {
    console.error('Baidu Map not loaded')
    return
  }

  try {
    const map = new window.BMap.Map(mapContainer.value)
    
    // 优先使用store中的经纬度数据
    if (locationData.value && locationData.value.latitude && locationData.value.longitude) {
      const point = new window.BMap.Point(locationData.value.longitude, locationData.value.latitude)
      map.centerAndZoom(point, 16)
      map.addOverlay(new window.BMap.Marker(point))
      
      // 添加地图控件
      map.addControl(new window.BMap.NavigationControl())
      map.addControl(new window.BMap.ScaleControl())
      map.enableScrollWheelZoom()
    } else {
      // 如果没有经纬度，则使用地址解析
      const myGeo = new window.BMap.Geocoder()
      
      // 根据地址解析坐标
      myGeo.getPoint(props.address, (point: any) => {
        if (point) {
          map.centerAndZoom(point, 16)
          map.addOverlay(new window.BMap.Marker(point))
          
          // 添加地图控件
          map.addControl(new window.BMap.NavigationControl())
          map.addControl(new window.BMap.ScaleControl())
          map.enableScrollWheelZoom()
        } else {
          console.error('未能解析地址:', props.address)
        }
      })
    }
  } catch (error) {
    console.error('初始化百度地图失败:', error)
  }
}

onMounted(() => {
  // 动态加载百度地图脚本
  const script = document.createElement('script')
  script.src = `https://api.map.baidu.com/api?v=3.0&ak=URTOk3aJ8lIH1VLPSTeDWJkSGttQkphr&callback=initBaiduMap`
  script.async = true
  
  // 在全局定义回调函数
  window.initBaiduMap = () => {
    initMap()
  }
  
  // 添加脚本到文档
  document.body.appendChild(script)
  
  // 添加脚本到文档
  document.body.appendChild(script)
})

// 监听地址变化或位置数据变化
watch([() => props.address, locationData], () => {
  // 确保BMap已经加载完成再初始化地图
  if (window.BMap !== undefined) {
    initMap()
  }
})

const navigateToHotel = () => {
  // 如果已经加载了百度地图API
  if (typeof window.BMap !== 'undefined') {
    try {
      // 优先使用locationData中的经纬度
      if (locationData.value && locationData.value.latitude && locationData.value.longitude) {
        // 构造导航URL
        const latitude = locationData.value.latitude;
        const longitude = locationData.value.longitude;
        const address = locationData.value.address || props.address;
        
        // 打开百度地图网页版导航
        window.open(`https://map.baidu.com/dir/?origin=我的位置&destination=${latitude},${longitude}&destinationAddress=${encodeURIComponent(address)}&mode=driving`, '_blank');
      } else {
        // 如果没有经纬度，则使用地址直接导航
        const address = locationData.value?.address || props.address;
        window.open(`https://map.baidu.com/dir/?origin=我的位置&destination=${encodeURIComponent(address)}&mode=driving`, '_blank');
      }
    } catch (error) {
      console.error('导航失败:', error);
    }
  } else {
    // 如果百度地图API未加载，直接使用地址导航
    const address = locationData.value?.address || props.address;
    window.open(`https://map.baidu.com/dir/?origin=我的位置&destination=${encodeURIComponent(address)}&mode=driving`, '_blank');
  }
}

// 检查是否有交通信息数据
const hasTransportationData = computed(() => {
  if (locationData.value && locationData.value.transportation) {
    const transportData = locationData.value.transportation;
    return Array.isArray(transportData) && transportData.length > 0;
  }
  return false;
});

// 检查是否有周边设施数据
const hasAttractionsData = computed(() => {
  if (locationData.value && locationData.value.attractions) {
    const attractionsData = locationData.value.attractions;
    return Array.isArray(attractionsData) && attractionsData.length > 0;
  }
  return false;
});
</script>

<style scoped>
.hotel-location {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 16px;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.section-icon {
  font-size: 24px;
  color: #1890ff;
}

h2 {
  font-size: 20px;
  margin: 0;
  color: #262626;
  font-weight: 600;
}

.location-container {
  display: grid;
  grid-template-columns: 3fr 2fr;
  gap: 24px;
  margin-bottom: 32px;
}

.map-container {
  height: 500px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0,0,0,0.06);
  transition: all 0.3s ease;
}

.map-container:hover {
  box-shadow: 0 4px 16px rgba(0,0,0,0.1);
}

.location-info {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.address-card,
.transportation-card,
.nearby-card {
  background: #fff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.06);
  transition: all 0.3s ease;
}

.address-card:hover,
.transportation-card:hover,
.nearby-card:hover {
  box-shadow: 0 4px 16px rgba(0,0,0,0.1);
  transform: translateY(-2px);
}

/* 添加固定高度的内容区域 */
.transportation-card :deep(.ant-tabs-content) {
  min-height: 150px;
}

/* 确保tab内容有固定宽度 */
.transportation-card :deep(.ant-tabs-tabpane) {
  width: 100%;
}

/* 确保标签栏样式一致 */
.transportation-card :deep(.ant-tabs-nav) {
  margin-bottom: 16px;
}

/* 修复标签省略号问题 */
.custom-tabs :deep(.ant-tabs-tab) {
  padding: 8px 16px;
  min-width: 80px;
  text-align: center;
}

.custom-tabs :deep(.ant-tabs-nav-operations) {
  display: none !important; /* 隐藏省略号操作按钮 */
}

h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  color: #262626;
  font-weight: 500;
}

.address {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 24px;
  color: #595959;
  line-height: 1.6;
}

.address .anticon {
  margin-top: 4px;
  color: #1890ff;
}

.navigation-btn {
  width: 100%;
}

.transport-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.transport-list li {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
  color: #595959;
}

.transport-list li:last-child {
  border-bottom: none;
}

.transport-icon {
  color: #1890ff;
}

.nearby-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.nearby-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: #f5f5f5;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.nearby-item:hover {
  background: #e6f7ff;
}

.nearby-icon {
  color: #1890ff;
  font-size: 18px;
}

.empty-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
  color: #aaa;
  text-align: center;
}

.empty-icon {
  font-size: 24px;
  margin-bottom: 10px;
}

.empty-info p {
  margin: 0;
}

@media (max-width: 992px) {
  .location-container {
    grid-template-columns: 1fr;
  }
  
  .map-container {
    height: 400px;
  }
}

@media (max-width: 576px) {
  .nearby-grid {
    grid-template-columns: 1fr;
  }
}
</style> 